package com.bjsxt.ssm.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bjsxt.ssm.bean.TbRole;
import com.bjsxt.ssm.bean.TbUser;
import com.bjsxt.ssm.mapper.TbRoleMapper;
import com.bjsxt.ssm.service.TbRoleService;

@Service
public class TbRoleServiceImpl implements TbRoleService {
	
	@Autowired
	private TbRoleMapper tbRoleMapper;

	@Override
	public int saveTbRole(TbRole role) {
		if(null==role){
			return -1;
		}
		// 对象属性判空
		if (StringUtils.isBlank(role.getRoleName())) {
					// TODO 抛异常
			return -1;
		}
		
		if (0 < role.getRoleId()) {
			// TODO 抛异常
			return -1;
		}
		List<TbRole> roles = tbRoleMapper.selectTbRoleByRoleName(role.getRoleName());
		if (CollectionUtils.isNotEmpty(roles)) {
			return -1;
		}

		this.tbRoleMapper.insertTbRole(role);
		return role.getRoleId();
	}

	@Override
	public void deleteTbRole(int roleid) {
		this.tbRoleMapper.deleteTbRole(roleid);
	}

	@Override
	public int updateTbRole(TbRole tbRole) {

		if (null == tbRole) {
			return -1;
		}
		if (0 >= tbRole.getRoleId()) {
			return -1;
		}
		// 对象属性判空
		if (StringUtils.isBlank(tbRole.getRoleName())) {
			// TODO 抛异常
			return -1;
		}

		TbRole orginal = tbRoleMapper.selectTbRole(tbRole.getRoleId());
		if (null == orginal) {
			return -1;
		}

		if (!orginal.getRoleName().equals(tbRole.getRoleName())) {
			/***
			 * 检查用户名是否已注册过
			 */
			List<TbRole> roles = tbRoleMapper.selectTbRoleByRoleName(tbRole.getRoleName());
			if (CollectionUtils.isNotEmpty(roles)) {
				return -1;
			}
		}

		this.tbRoleMapper.updateTbRole(tbRole);

		return 1;
	}

	@Override
	public TbRole selectTbRole(int roleId) {
		return tbRoleMapper.selectTbRole(roleId);
	}

	@Override
	public int queryCount() {
		int rst=tbRoleMapper.queryTbRoleCount();
		return rst;
	}

	@Override
	public List<TbRole> pagination(Integer pageSize, Integer page) {
		if (0 >= pageSize || 0 >= page) {
			return null;
		}
		int limit = (page - 1) * pageSize;
		Map<String, Integer> query = new HashMap<>();
		query.put("pageSize", pageSize);
		query.put("limit", limit);
		List<TbRole> rst=tbRoleMapper.pagination(query);
		return rst;
	}
	

	@Override
	public int deleteTbRole(Integer[] roleIds) {
		if(ArrayUtils.isEmpty(roleIds)){
			return -1;
		}
		int i=0;
		for(Integer id:roleIds){
			this.deleteTbRole(id);
			i++;
		}
		return i;
	}

	@Override
	public List<TbRole> queryAll() {
		return tbRoleMapper.queryAll();
	}

	@Override
	public List<TbRole> selectTbRoleByRoleName(String roleName) {
		
		return this.tbRoleMapper.selectTbRoleByRoleName(roleName);
	}

}
